import { Inject } from '@midwayjs/core';
import { CoolController, BaseController } from '@cool-midway/core';
import { ProductStockEntity } from '../../entity/stock';
import { ProductStockService } from '../../service/stock';
import { ProductProductEntity } from '../../entity/product';

/**
 * 库存信息
 */
@CoolController({
  api: ['add', 'delete', 'update', 'info', 'list', 'page'],
  entity: ProductStockEntity,
  service: ProductStockService,
  pageQueryOp: {
    where: async ctx => {
      const {
        quantityStart,
        quantityEnd,
        lastStockChangeStartTime,
        lastStockChangeEndTime,
        isWarning,
      } = ctx.request.body;
      const where = [];

      if (quantityStart && quantityEnd) {
        where.push([
          'a.currentStockQuantity >= :quantityStart AND a.currentStockQuantity <= :quantityEnd',
          { quantityStart, quantityEnd },
        ]);
      }

      if (lastStockChangeStartTime && lastStockChangeEndTime) {
        where.push([
          'a.lastStockChangeTime >= :lastStockChangeStartTime AND a.lastStockChangeTime <= :lastStockChangeEndTime',
          { lastStockChangeStartTime, lastStockChangeEndTime },
        ]);
      }

      if (isWarning) {
        where.push(['a.currentStockQuantity < a.stockWarningThreshold', {}]);
      }

      return where;
    },
    join: [
      {
        entity: ProductProductEntity,
        alias: 'b',
        condition: 'a.productId = b.id',
        type: 'leftJoin',
      },
    ],
    select: ['a.*', 'b.name as productName'],
  },
})
export class AdminProductStockController extends BaseController {
  @Inject()
  productStockService: ProductStockService;
}
